/*
 * sch.c
 *
 * Created: 2014-10-9 15:00:47
 *  Author: Administrator
 */ 
#include "schedule.h"

sTask SCH_tasks_G[SCH_MAX_TASKS];
	
u8 SCH_Add_Task(void(*pFunction)(),u32 Delay,u32 Peroid,s8 RunNum)
{
	u8 Index = 0;
	while((SCH_tasks_G[Index].pTask != 0) && (Index < SCH_MAX_TASKS))	
	{
		Index++;
	}
	if(Index == SCH_MAX_TASKS)
	{
		return SCH_MAX_TASKS;
	}
	SCH_tasks_G[Index].pTask = pFunction;
	SCH_tasks_G[Index].Delay = Delay;
	SCH_tasks_G[Index].Peroid = Peroid;
	SCH_tasks_G[Index].RunMe = 0;
	SCH_tasks_G[Index].RunNum = RunNum;
	return Index;
}
void SCH_Updata_Tasks(void)
{
	u8 Index;
	for(Index = 0;Index < SCH_MAX_TASKS;Index++)
	{
		if(SCH_tasks_G[Index].pTask)
		{
			if(SCH_tasks_G[Index].Delay == 0)
			{
				SCH_tasks_G[Index].RunMe++;
				if(SCH_tasks_G[Index].Peroid)
				{
					SCH_tasks_G[Index].Delay = SCH_tasks_G[Index].Peroid;
				}
			}
			else
			{
				SCH_tasks_G[Index].Delay--;
			}
		}
	}
}
void SCH_Dispatch_Tasks(void)
{
	u8 Index;
	for(Index = 0;Index < SCH_MAX_TASKS;Index++)
	{
		if(SCH_tasks_G[Index].RunMe > 0)
		{
			SCH_tasks_G[Index].pTask();
			SCH_tasks_G[Index].RunMe--;
			if(SCH_tasks_G[Index].RunNum > 0)
			{
				SCH_tasks_G[Index].RunNum--;
				if(SCH_tasks_G[Index].RunNum == 0)
				{
					SCH_Delete_Tasks(Index);
				}
					
			}
			if(SCH_tasks_G[Index].Peroid == 0)
			{
				SCH_Delete_Tasks(Index);
			}
		}
	}
}
void SCH_Delete_Tasks(u8 Index)
{
	SCH_tasks_G[Index].pTask = 0;
	SCH_tasks_G[Index].Delay = 0;
	SCH_tasks_G[Index].Peroid = 0;
	SCH_tasks_G[Index].RunMe = 0;
	SCH_tasks_G[Index].RunNum = 0;
}
